package de.homelabs.moonrat;

import javax.annotation.PostConstruct;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import de.homelabs.moonrat.config.MoonratConfigurationManager;
import de.homelabs.moonrat.config.MoonratStartupConfig;
import de.homelabs.moonrat.context.DataProviderService;
import de.homelabs.moonrat.template.freemarker.MoonratFreemarkerTemplateLoader;

/**
 * Responsible for bootstrapping the Moonrat context.
 * Ensures the correct bootstrapping workflow
 * 
 * Uses Spring {@link PostConstruct}
 *  
 * @author D.Mueller
 *
 */
@Service
public class MoonratBootstrap implements ApplicationContextAware {

	//vars
	static Logger logger = Logger.getLogger(MoonratBootstrap.class);
	
	@Autowired
	MoonratConfigurationManager mRConfigManager;
	
	@Autowired
	DataProviderService mRDpService;
	
	@Autowired
	MoonratFreemarkerTemplateLoader mRFreemakerTPLLoader;
	
	@Autowired
	MoonratStartupConfig mRStartupConfig;
	
	ApplicationContext applicationContext;
	
	/**
	 * constructor
	 */
	public MoonratBootstrap(){}
	
	@PostConstruct
	protected void postConstruct(){
		try {
			//config setup
			mRConfigManager.initConfig(mRStartupConfig);
			
			//data provider setup
			mRDpService.initDataProvider(applicationContext);
			
			//templateLoader setup
			mRFreemakerTPLLoader.initTemplateDataProvider();
			
		} catch (Exception e){
			logger.error("Can not bootstrap application: "+e.getMessage());
		}
	}

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.applicationContext = context;
	}
}
